package com.example.lottery.common.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
@Slf4j
@Configuration
public class CapthchaUtil {
    @Value("${captcha.width}")
    private int CAPTCHA_WIDTH;
    @Value("${captcha.height}")
    private int CAPTCHA_HEIGHT;

    /**
     * 创建验证码并返回
     * @param httpServletResponse
     * @return
     */
    public String createCaptcha(HttpServletResponse httpServletResponse){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
        //图形验证码写出，可以写出到文件，也可以写出到流
        try {
            lineCaptcha.write(httpServletResponse.getOutputStream());
            httpServletResponse.setHeader("Param","No-cache");
            httpServletResponse.setContentType("image/jpeg");
            httpServletResponse.getOutputStream().close();
            //输出code
            return lineCaptcha.getCode();
        } catch (IOException e) {
            log.warn("验证码输出流异常");
            return null;
        }
    }
}
